﻿using UnityEngine;
using System.Collections;
using System.IO;
public class UpdaterDownload : MonoBehaviour {

	// Use this for initialization
	void Start () {
		Invoke("StartDownloadUpdater",3);
	}
	
	// Update is called once per frame
	void Update () {
	
	}
	
	void StartDownloadUpdater()
	{
		StartCoroutine(	BeginDowload());
	}
	
	
	
	public int localver;
	public int remotver;
	IEnumerator BeginDowload()
	{
		string strlv ="file:///"+ Application.dataPath + "/../ver_updater_local.txt" ;
		WWW wwwlv = new WWW( strlv );
		yield return wwwlv;		
		if(wwwlv.isDone && wwwlv.error==null)
		{
			localver =  int.Parse( wwwlv.text);
		}
		else
		{
			localver = 0;
		}
		wwwlv.Dispose();
		
		string rh =  WebDownload.GetInstance().webservername + "../ver_updater.txt";
		WWW wwwrv = new WWW(rh);
		yield return wwwrv;
		
		if(wwwrv.isDone )
		{
			if(wwwrv.error==null)
			{
				remotver = int.Parse(wwwrv.text);
			}
			else
			{
				Debug.Log("download  ver_update faild!");
			}
		}
		wwwrv.Dispose();
		
		if(remotver>localver)
		{
			StartCoroutine(tload());
		}
	}
	
	IEnumerator tload()
	{
		string str_lname =WebDownload.GetInstance().webservername+"../launch.exe";
		WWW wwwut = new WWW(str_lname);
		yield return wwwut;
		if(wwwut.isDone)
		{
	    	SaveFile(wwwut.bytes,"launch.exe");
		}
		wwwut.Dispose();
		
		WWW wwwconf = new WWW(WebDownload.GetInstance().webservername+"../config.ini");
		yield return wwwconf;
		if(wwwconf.isDone)
		{
			SaveFile(wwwconf.bytes,"config.ini");	
		}
		wwwconf.Dispose();
		
		WWW wwwxpk = new WWW(WebDownload.GetInstance().webservername+"../AXpkLib.dll");
		yield return wwwxpk;
		if(wwwxpk.isDone)
		{
			SaveFile(wwwxpk.bytes,"axpklib.dll");	
		}
		wwwxpk.Dispose();
		
		string rh =  WebDownload.GetInstance().webservername + "../ver_updater.txt";
		WWW wwwrv = new WWW(rh);
		yield return wwwrv;
		if(wwwrv.isDone)
		{
			SaveFile(wwwrv.bytes,"ver_updater_local.txt");
		}
		wwwrv.Dispose();

	}
	void SaveFile(byte[] bytes,string filename)
	{
		if(bytes!=null)
		{
	        using (FileStream fs = System.IO.File.Create(filename))
	        {
	            fs.Write(bytes, 0, bytes.Length);
	        }
		}
		else
		{
			Debug.LogError( "launch download faild");		
		}
			
	}
}
